#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <assert.h>
#include <semaphore.h>
#include <fcntl.h>

#define IPCKEY 0x100

void* create_shm_buf(void);
sem_t* create_sem(void);

int main()
{
    unsigned char* shm_buf = create_shm_buf();
    sem_t* sem = create_sem();
    int i;
    for(i=0; ; i++)
    {
        sem_wait(sem);
        *(int*)(shm_buf)    = i;
        *(int*)(shm_buf+4)  = i;
        sem_post(sem);

        if(i>=1024*1024)
            i = 0;
    }

    return 0;
};


void* create_shm_buf(void)
{
    void* buf;

    #define SHM_SIZE    102400
    int shm_id = shmget(IPCKEY, SHM_SIZE, 0640|IPC_CREAT|IPC_EXCL);
    assert(shm_id != -1);

    buf = shmat(shm_id, NULL, 0);
    printf("======%s OK.\n", __FUNCTION__);

    return buf;
}


sem_t* create_sem(void)
{
    sem_t* sem ;

    int flag = O_RDWR | O_CREAT ;
    //sem = sem_open("test1", flag, S_IRUSR | S_IWUSR, 1);
    sem = sem_open("test2", flag, 0640, 1);
    assert(NULL != sem);

    printf("======%s OK.\n", __FUNCTION__);

    return sem;
}
